package com.xmjs.baselibrary.base.dialog;

import android.app.Dialog;
import android.content.Context;
import android.view.MotionEvent;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

/**
 * Dialog随手指上下移动
 */
public class TouchMoveDialog extends Dialog {
    //每次移动距离
    private double moveDistance;
    //手指按下时的Y坐标
    private float downY;

    public TouchMoveDialog(@NonNull Context context) {
        super(context);
    }

    public TouchMoveDialog(@NonNull Context context, int themeResId) {
        super(context, themeResId);
    }

    protected TouchMoveDialog(@NonNull Context context, boolean cancelable, @Nullable OnCancelListener cancelListener) {
        super(context, cancelable, cancelListener);
    }

    /**
     * 重写onTouchEvent实现Dialog随手指上下移动
     *
     * @param event
     * @return
     */
    @Override
    public boolean onTouchEvent(@NonNull MotionEvent event) {
        View view = getWindow().getDecorView();
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                downY = event.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                int left = 0;
                int top = (int) event.getY();
                top = top < 0 ? 0 : top;
                int right = left + view.getWidth();
                int bottom = top + view.getHeight();
                view.layout(left, top, right, bottom);
                break;
            case MotionEvent.ACTION_UP:
                moveDistance = Math.sqrt(Math.pow(downY, 2) + Math.pow(event.getY(), 2));
                //滑动距离超过1/4就关闭，否则反弹回原位
                if (moveDistance > view.getHeight() / 4) {
                    dismiss();
                } else {
                    view.layout(0, 0, view.getWidth(), view.getHeight());
                }
                break;
        }
        return super.onTouchEvent(event);
    }
}
